package com.seadragon.app.ksr.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.seadragon.app.ksr.model.Customer;
import com.seadragon.app.ksr.model.KsrConstants;
import com.seadragon.app.ksr.service.CustomerService;
import com.seadragon.app.ksr.util.GsonUtils;

@Controller
public class CustomerController {
	private static Logger logger = LoggerFactory.getLogger(CustomerController.class);

	
	@Autowired
	private CustomerService customerService;


	@RequestMapping(value = {"/customer/profile/get.json"}, method = RequestMethod.GET)
	public @ResponseBody
	String getCustomerProfileJson(HttpServletRequest request, HttpSession session) {
		String customerJson = null;
		if (session.getAttribute(KsrConstants.SESSION_SCOPED_CUSTOMER) != null) {
			Customer customer = (Customer )session.getAttribute(KsrConstants.SESSION_SCOPED_CUSTOMER);
			customerJson = GsonUtils.ObjectToGson(customer);
		}
		return customerJson;
	}	
	
	
	@RequestMapping(value = {"/customer/profile/{id}/get.json"}, method = RequestMethod.GET)
	public @ResponseBody
	String getCustomerProfileJsonById(HttpServletRequest request, HttpSession session,@PathVariable long id) {
		String customerJson = null;
		Customer customer = customerService.findById(id);
		if (customer != null) {
			customerJson = GsonUtils.ObjectToGson(customer);
		}
		return customerJson;
	}	
	//update or create a customer
	@RequestMapping(value = "/customer/profile/save.json", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject saveBusinessProfile(@RequestBody String json,HttpSession session) {
		logger.debug(json);
		Customer customer = (Customer)GsonUtils.GsonToObject(json, Customer.class);
				
		
		if (customer.getId()>0)
			customerService.update(customer);
		else
			customerService.save(customer);
		
		session.setAttribute(KsrConstants.SESSION_SCOPED_CUSTOMER, customer);
		
		JSONObject data = new JSONObject();
		data.put("status", "ok");
	return data;
}
}
